package com.video.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.video.entity.FileEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * @author maomao
 */
@Slf4j
@Service
public class FileEntityService {
    @Value("${filelib.storageType}")
    private String storageType;

    @Value("${filelib.alioss.url}")
    private String endpoint;

    @Value("${filelib.alioss.accessKeyId}")
    private String accessKeyId;

    @Value("${filelib.alioss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${filelib.alioss.bucketName}")
    private String bucketName;

    public FileEntity addFileEntity(MultipartFile file) throws IOException {
        FileEntity fileEntity = null;
        if (StorageType.ALIOSS.equals(StorageType.valueOf(storageType))) {
            fileEntity = upload2Oss(file.getInputStream(), file.getOriginalFilename(), file.getContentType(), file.getSize());
        }

        return fileEntity;
    }

    public FileEntity addFileEntity(File file, String fileType) throws FileNotFoundException {

        FileEntity fileEntity = null;

        if (StorageType.ALIOSS.equals(StorageType.valueOf(storageType))) {
            InputStream inputStream = new FileInputStream(file);
            long length = file.length();
            String name = file.getName();
            fileEntity = upload2Oss(inputStream, name, fileType, length);
        }


        return fileEntity;
    }


    private FileEntity upload2Oss(InputStream inputStream, String fileName, String fileType, long size) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            String entityId = UUID.randomUUID().toString();

            String basePath = entityId.substring(0, 2) + "/" + entityId.substring(entityId.length() - 2) + "/";
            String entityIdWithType = basePath + entityId + fileName.substring(fileName.lastIndexOf("."));

            ossClient.putObject(bucketName, entityIdWithType, inputStream);

            log.info("upload video file {} to oss", fileName);

            FileEntity fileEntity = new FileEntity();
            fileEntity.setEntityId(entityId);

            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
            URL url = ossClient.generatePresignedUrl(bucketName, entityIdWithType, expiration);
            if (url != null && url.toString().split("\\?").length > 0) {
                String uploadUrl = url.toString().split("\\?")[0];
                fileEntity.setEntityPath(uploadUrl);
                fileEntity.setDownloadUrl(uploadUrl);
            } else {
                log.error("get url from oss failed,file : {}", fileName);
            }
            fileEntity.setStorageLocation(StorageType.ALIOSS.getValue());
            fileEntity.setEntityName(fileName);
            fileEntity.setFileType(fileType);
            fileEntity.setSize(size);

            return fileEntity;
        } catch (Exception e) {
            log.error("upload to oss failed,file : {}", fileName);
            throw e;
        } finally {
            ossClient.shutdown();
        }
    }

    enum StorageType {

        /**
         * 阿里云存储
         */
        ALIOSS(1);

        private final int value;

        StorageType(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }
}
